#!/bin/bash

# ************* Assumptions *************
# 1. This script is running in the same 
# directory as the client program and
# any other executables required by
# this script. 
# 2. The "servers" variable list must be
# seeded with the correct IP addresses.
# 3. The port number is also provided.
# 4. You can adjust the number of
# iterations, the default is 100.
# ***************************************


# user adjustable variables
servers=( 172.16.11.149 172.16.11.151 172.16.11.148 172.16.11.150 )
port=( 12345 12345 12345 12345 )
numIterations=100

# program variables
correctResult=0
incorrectResult=0
incorrectCount=0
highIncorrectCount=0
noResponse=0

# hash table implementation
hput () {
  eval hash"$1"='$2'
}

hget () {
  eval storedValue='${hash'"$1"'#hash}'
  if [[ "$storedValue" = "$2" || "$storedValue" = "" ]]
  then
      correctResult=$(($correctResult + 1))
      incorrectCount=0
  else
      incorrectResult=$(($incorrectResult + 1))
      incorrectCount=`expr $incorrectCount + 1`
      if [ "$highIncorrectCount" -lt "$incorrectCount" ]
      then
	  highIncorrectCount=$incorrectCount
      fi
  fi
}

# Show consistency capabilities
echo "Testing Consistency"
# execute many requests from the client
for (( c=0; c<$numIterations; c++ ))
do
        # uncomment the line below for printing of current iteration
        # echo $c
	# generate random number for server selection
	n=$(($RANDOM % 4))
	# generate the random key
	k=$(($RANDOM % 4 + 1)) #8 + 1))
	export key=`./generateString $k`
	# generate the random value
	v=$(($RANDOM % 20 + 1)) #48 + 1))
	export value=`./generateString $v`
	# pick get or set operation (get = 0, set = 1)
	getOrSet=$(($RANDOM % 2))
	if [ "$getOrSet" -eq 0 ] 
	then
		# invoke the client program for get
		export rt=`./client -h ${servers[$n]}:${port[$n]} -k $key | grep "\["`
		export retrievedValue=`python getValue.py $rt`
		if [ "$retrievedValue" = "[[" ]
		then
		    noResponse=`expr $noResponse + 1`
		else
		    hget $key $retrievedValue
		fi
	else # $getOrSet = 1
		# invoke the client program for set
		export rt=`./client -h ${servers[$n]}:${port[$n]} -k $key -v $value | grep "\["`
		export retrievedValue=`python getValue.py $rt`
		if [ "$retrievedValue" = "[[" ]
                then
                    noResponse=`expr $noResponse + 1`
                else
		    hget $key $retrievedValue
		    hput $key $value
		fi
	fi
done

# print the results
echo "For" $numIterations "get or set operations:" 
echo $correctResult "returned the correct value, and" 
echo $incorrectResult "returned the incorrect value"
echo "The maximum incorrect results in a row was" $highIncorrectCount
echo "No response from" $noResponse
